<template>
  <div 
    v-if="visible" 
    ref="popupRef" 
    class="selection-popup"
    :style="popupStyle"
  >
    <div class="popup-content">
      <slot>
        <!-- 显示搜索结果 -->
        <div v-if="searchResults" class="results-container">
          <pre class="results-pre">{{ searchResults }}</pre>
        </div>
        <div v-else>
          <p>正在搜索中...</p>
        </div>
        <el-button @click="close">关闭</el-button>
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
// import {searchPopup} from '@/stores/searchPopup'


const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  selectedText: {
    type: String,
    default: ''
  },
  editorInstance: {
    type: Object,
    required: true
  },
  searchResults: [String, Object]
})

const emit = defineEmits(['update:visible'])

const popupRef = ref<HTMLElement | null>(null)
const popupStyle = ref({
  left: '0',
  top: '0'
})

// 关闭弹窗
const close = () => {
  emit('update:visible', false)
}

// 更新弹窗位置 - 确保在文本右上方且不遮挡
const updatePopupPosition = () => {
  nextTick(() => {
    if (!props.editorInstance || !popupRef.value) return;

    const { view } = props.editorInstance;
    const { from, to } = view.state.selection;

    // 获取选中文本的边界矩形
    const start = view.coordsAtPos(from);
    const end = view.coordsAtPos(to);
    
    // 计算弹窗应该出现的位置
    const popupRect = popupRef.value.getBoundingClientRect();
    const popupWidth = popupRect.width;
    const popupHeight = popupRect.height;

    // 默认位置：选中文本的右上方
    let left = end.right + 5; // 右侧+5px间距
    let top = Math.min(start.top, end.top) - popupHeight - 5; // 最上方的行-top-5px间距

    // 边界检测
    // 如果右侧空间不足，移到左侧
    if (left + popupWidth > window.innerWidth) {
      left = start.left - popupWidth - 5;
    }
    
    // 如果上方空间不足，移到下方
    if (top < 0) {
      top = Math.max(start.bottom, end.bottom) + 5;
    }

    // 确保不会遮挡选中文本
    // 检查水平方向是否遮挡
    if (left < end.right && left + popupWidth > start.left) {
      // 如果会水平遮挡，移到上方或下方
      if (top < start.top) {
        // 已经在上面，就移到下面
        top = Math.max(start.bottom, end.bottom) + 5;
      } else {
        // 已经在下面，就移到上面
        top = Math.min(start.top, end.top) - popupHeight - 5;
      }
    }

    popupStyle.value = {
      left: `${left}px`,
      top: `${top + window.scrollY}px`,
    };
  });
};

// 监听滚动以更新位置
const handleScroll = () => {
  if (props.visible) {
    updatePopupPosition()
  }
}

// 监听窗口大小变化
const handleResize = () => {
  if (props.visible) {
    updatePopupPosition()
  }
}

// 监听可见性变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    updatePopupPosition()
  }
})

// 监听选中文本变化
watch(() => props.selectedText, (newVal) => {
  if (!newVal) {
    close()
  }
})

onMounted(() => {
  window.addEventListener('scroll', handleScroll)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss">
.selection-popup {
  position: absolute;
  z-index: 9999;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  max-width: 300px;
  max-height: 400px;
  word-wrap: break-word;
  flex-direction: column;
}

.popup-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow: hidden;
  max-height: 400px;
}

.popup-content p {
  margin: 0;
  white-space: pre-wrap;
}

.results-container {
  width: 100%;
  overflow-y: auto;
}

.results-pre {
  white-space: pre-wrap; /* 保留空白符但允许换行 */
  word-wrap: break-word; /* 允许长单词或URL换行 */
  overflow-wrap: break-word; /* 更现代的换行属性 */
  font-family: inherit; /* 继承父元素字体 */
  margin: 0; /* 移除默认边距 */
  padding: 0; /* 移除默认内边距 */
  max-width: 100%; /* 确保不超过容器宽度 */
}
</style>